<?php
namespace logicmodel;


use comservice\GetRedis;
use comservice\Response;
use datamodel\Feedback;
use datamodel\Users;
use dh2y\qrcode\QRcode;
use logicmodel\award\Recommend;
use think\Db;

class UserLogic
{

    private $usersData;
    public function __construct()
    {
        $this->usersData = new Users();
    }

    /**
     * 注册
     * @param $uuid
     * @param $phone
     * @param $password
     * @param $pay_password
     * @param $code
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function register($uuid,$phone,$password,$pay_password,$code){
        $result = validateCode($phone,$code,1);
        if(!$result) return Response::fail('验证码输入错误');
        $info = $this->usersData->where(['phone'=>$phone,'is_del'=>0])->find();
        if($info) return Response::fail('手机号已注册');
        if(!empty($uuid)){
            $parentInfo = $this->usersData->where(['uuid'=>$uuid,'is_del'=>0])->find();
        }else{
            $parentInfo = $this->usersData->where(['id'=>1,'is_del'=>0])->find();
        }
        if(empty($parentInfo)) return Response::fail('邀请码错误');
        $nick_name = 'sp'.rand(11111,99999);
        $salt = rand(1111,9999);
        $pid = $parentInfo['id'];
        $data['phone'] = $phone;
        $data['salt'] = $salt;
        $data['password'] = md5(md5($password).$salt);
        $data['pay_salt'] = $salt;
        $data['pay_password'] = md5(md5($pay_password).$salt);
        $data['head_image'] = defaultImage();;
        $data['nick_name'] = $nick_name;
        $data['pid'] = $pid;
        $data['upid'] = $pid;
        $data['uuid'] = uuid();
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['parent_member'] = $parentInfo['phone'];
        Db::startTrans();
        $user_id = $this->usersData->saveEntityAndGetId($data);
        if($user_id > 0) {
            $result =  $this->updateGroup($pid);
            if($result){
                Db::commit();
                award($user_id);
                $remark = '推荐会员' . $nick_name . '注册奖励';
                (new Recommend())->award($pid,$user_id,$remark);
                return Response::success('注册成功');
            }
            Db::rollback();
            return Response::fail('注册失败');

        }
        Db::rollback();
        return Response::fail('注册失败');
    }

    /**
     * 更新团队信息
     * @param $pid
     * @return bool
     * @throws \think\Exception
     */
    private function updateGroup($pid)
    {
        $field = ['id', 'pid', 'upid'];
        $userData = (new MemberLogic())->listParent($pid, $field, 1, 0);
        $groupArr = array_column($userData, 'id');
        $where['id']  = ['in', $groupArr];
        $result = $this->usersData->updateForInc($where, 'group_person_count', 1); //修改团队成员
        $res = $this->usersData->updateForInc(['id' => $pid], 'total_direct', 1);//修改直推人数
        if ($result > 0 && $res > 0) return true;
        return false;
    }

    /**
     * 忘记密码
     * @param $phone
     * @param $code
     * @param $password
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function forgetPassword($phone,$code,$password){
        $result = validateCode($phone,$code,2);
        if($result == false) return Response::fail('验证码输入错误');
        $userInfo =  $this->usersData->where(['phone'=>$phone,'is_del'=>0])->find();
        if(empty($userInfo)) return Response::fail('手机号/账号未注册');
        $salt = rand(1111,9999);
        $data['password'] = md5(md5($password).$salt);
        $data['salt'] = $salt;
        $result = $this->usersData->updateByWhere(['id'=>$userInfo['id']],$data);
        if($result) return Response::success('修改成功');
        return Response::fail('修改失败');
    }


    /**
     * 会员登录
     * @param $phone
     * @param $password
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function login($phone,$password){
        $userInfo = $this->usersData->where(['phone'=>$phone,'is_del'=>0])->find();
        if(empty($userInfo)) return Response::fail('手机号未注册');
        if($userInfo['status'] == 0) return Response::fail('账户已冻结');
        if(md5(md5($password).$userInfo['salt']) != $userInfo['password']) return  Response::fail('密码错误');

        $app_token = uniqueNum();
        $redis = GetRedis::getRedis();
        $redis->setItem('app_'.$app_token,$userInfo['id']);
        $result = $this->usersData->updateByWhere(['id'=>$userInfo['id']],['app_token'=>$app_token,'login_time'=>date('Y-m-d H:i:s')]);
        if($result) return Response::success('登录成功',['app_token'=>$app_token]);
        return Response::fail('登录失败');
    }

    /**
     * 手机号登录
     * @param $phone
     * @param $code
     * @param $uuid
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function phoneLogin($phone,$code,$uuid){
        $result = validateCode($phone,$code,3);
        //  if(!$result) return Response::fail('验证码输入错误');
        $userInfo = $this->usersData->where(['phone'=>$phone,'is_del'=>0])->find();
        if($userInfo) {
            if($userInfo['status'] == 0) return Response::fail('账户已冻结');
            $app_token = uniqueNum();
            $redis = GetRedis::getRedis();
            $redis->setItem('app_'.$app_token,$userInfo['id']);
            $result = $this->usersData->updateByWhere(['id'=>$userInfo['id']],['app_token'=>$app_token,'login_time'=>date('Y-m-d H:i:s')]);
            if($result) return Response::success('登录成功',['app_token'=>$app_token]);
            return Response::fail('登录失败');
        }else{
            if(!empty($uuid)){
                $parentInfo = $this->usersData->where(['uuid'=>$uuid,'is_del'=>0])->find();
            }
            if(empty($parentInfo))  $parentInfo = $this->usersData->find();
            if(empty($parentInfo)) return Response::fail('邀请码错误');

            $account = (new WalletLogic())->newAccount();
            if($account !== false){
                $data['wallet_address'] = $account['address'];
                $data['wallet_private_key'] = $account['private_key'];
            }
            $nick_name  =  'SKY'.rand(111111,999999);
            $pid = $parentInfo['id'];
            $data['phone'] = $phone;
            $data['head_image'] = defaultImage();;
            $data['nick_name'] =  'SKY'.rand(111111,999999);
            $data['pid'] = $pid;
            $data['upid'] = $pid;
            $data['uuid'] = uuid();
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['parent_member'] = $parentInfo['phone'];
            Db::startTrans();
            $user_id = $this->usersData->saveEntityAndGetId($data);
            if($user_id > 0) {
                $result =  $this->updateGroup($pid);
                if($result){
                    Db::commit();
                    award($user_id);
                    $remark = '推荐会员' . $nick_name . '注册奖励';
                    (new Recommend())->award($pid,$user_id,$remark);
                    return Response::success('注册成功');
                }
                Db::rollback();
                return Response::fail('注册失败');

            }
            Db::rollback();
            return Response::fail('注册失败');


        }
    }

    /**
     * 修改登录密码
     * @param $userInfo
     * @param $code
     * @param $password
     * @param $password_re
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updatePassword($userInfo,$code,$password,$password_re){
        $result = validateCode($userInfo['phone'],$code,2);
        if($result == false) return Response::fail('验证码输入错误');
        if($password != $password_re) return Response::fail('两次密码输入不一致');
        $salt = rand(1111,9999);
        $password = md5(md5($password).$salt);
        $data['salt'] = $salt;
        $data['password'] = $password;
        $result = $this->usersData->updateByWhere(['id'=>$userInfo['id']],$data);
        if($result > 0) return Response::success('修改成功');
        return Response::fail('修改失败');
    }

    /**
     * 修改资金密码
     * @param $userInfo
     * @param $code
     * @param $pay_password
     * @param $pay_password_re
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updatePayPassword($userInfo,$code,$pay_password,$pay_password_re){
        $result = validateCode($userInfo['phone'],$code,2);
        if($result == false) return Response::fail('验证码输入错误');
        if($pay_password != $pay_password_re) return Response::fail('两次密码输入不一致');
        $uid = $userInfo['id'];
        $salt = rand(1111,9999);
        $password = md5(md5($pay_password).$salt);
        $data['pay_salt'] = $salt;
        $data['pay_password'] = $password;
        $result = $this->usersData->updateByWhere(['id'=>$uid],$data);
        if($result > 0) return Response::success('修改成功');
        return Response::fail('修改失败');
    }

    /**
     * 会员信息
     * @param $userInfo
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function userInfo($userInfo){
        if(empty($userInfo['phone'])) return Response::bindPhone('请先绑定手机号');
        $data['head_image'] = $userInfo['head_image'];
        $data['nick_name'] = $userInfo['nick_name'] ;
        $data['phone'] = $userInfo['phone'];
        $data['uuid'] = $userInfo['uuid'];
        $data['is_auth'] = $userInfo['is_auth'];
        $data['name'] = $userInfo['name'];
        $data['card'] = $userInfo['card'];
        $data['is_wx_auth'] = $userInfo['is_wx_auth'];
        $data['wallet_address'] = $userInfo['wallet_address'];
        $data = addWebSiteUrl($data,['head_image']);
        return Response::success('success',$data);
    }

    /**
     * 绑定手机号
     * @param $userInfo
     * @param $phone
     * @param $code
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function bindPhone($userInfo,$phone,$code){
        if(!empty($userInfo['phone'])) return  Response::fail('您已绑定手机号,请勿重复绑定');
        $result =  validateCode($phone,$code,3);
        if(!$result) return Response::fail('验证码输入错误');
        $info = $this->usersData->where(['phone'=>$phone,'is_del'=>0])->find();
        //判断是否绑定过手机号
        if(!empty($info)){
            $info = $info->toArray();
            //合并账号信息
            $result = $this->usersData->where(['id'=>$info['id']])
                ->update(['is_wx_auth'=>1,'wx_open_id'=>$userInfo['wx_open_id'],'nick_name'=>$userInfo['nick_name'],'head_image'=>$userInfo['head_image']]);
            if(!$result) return  Response::fail('绑定失败1');
            $this->usersData->where(['id'=>$userInfo['id']])->update(['is_del'=>1]);
            //生成token
            $user_id = $info['id'];
        }else{
            $result = $this->usersData->updateByWhere(['id'=>$userInfo['id']],['phone'=>$phone]);
            if(!$result) return Response::fail('绑定失败2');
            $user_id = $userInfo['id'];
        }
        $app_token = uniqueNum();
        $redis = GetRedis::getRedis();
        $redis->setItem('app_'.$app_token,$user_id);
        $this->usersData->updateByWhere(['id'=>$user_id],['app_token'=>$app_token]);
        return  Response::success('success',['app_token'=>$app_token]);
    }
    /**
     * 编辑会员信息
     * @param $uid
     * @param $nick_name
     * @param $head_image
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editUserInfo($uid,$nick_name,$head_image){
        $data['head_image'] = $head_image;
        $data['nick_name'] = $nick_name;
        $data = trimWebUrl($data,['head_image']);
        $result = $this->usersData->updateByWhere(['id'=>$uid],$data);
        if($result) return Response::success('success');
        return  Response::fail('编辑失败');
    }

    /**
     * 海报分享
     * @param $userInfo
     * @return array
     * @throws \think\Exception
     */
    public function share($userInfo){
        $data['uuid'] = $userInfo['uuid'];
        $url = config('site.share_url');
        $uuid = $userInfo['uuid'];
        $register_url = $url.'/#/pages/login/register?uuid='.$uuid;
        $code = new QRcode();
        $qr_code_img =  $code
            ->png($register_url,'uploads/qrcode/'.time().rand(11111,99999).'.png',6)
            ->getPath();
        $data['qr_code_image'] = $qr_code_img;
        $data['register_url'] = $register_url;
        $data = addWebSiteUrl($data,['qr_code_image']);
        return Response::success('success',$data);
    }

    /**
     * 团队信息
     * @param $uid
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function team($uid){
        $where['pid'] = $uid;
        $where['is_del'] = 0;
        $field  = ['phone','create_time','head_image'];
        $data =  $this->usersData
            ->where($where)
            ->field($field)
            ->order(['id desc'])
            ->select();
        if($data){
            $data = collection($data)->toArray();
            $data = addWebSiteUrl($data,['head_image']);
            return Response::success('success',$data);
        }
        return Response::success('暂无数据',[]);
    }

    /**
     * 问题反馈
     * @param $uid
     * @param $images
     * @param $remark
     * @return array
     */
    public function feedBack($uid,$images,$remark){
        $data['uid'] = $uid;
        $data['images'] = $images;
        $data['remark'] = $remark;
        $data['create_time'] = date('Y-m-d H:i:s');
        $data = trimWebUrl($data,['images']);
        $result = (new Feedback())->insertGetId($data);
        if($result) return Response::success('提交成功');
        return  Response::fail('提交失败');
    }

    /**
     * 反馈记录
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function feedBackList($uid){
        $where['uid'] = $uid;
        $where['is_del'] = 0;
        $data = (new Feedback())->where($where)
            ->field(['remark','images','reply','create_time'])
            ->order(['id desc'])
            ->select();
        if($data){
            $data = collection($data)->toArray();
            return Response::success('success',$data);
        }
        return Response::success('success',[]);
    }

    /**
     * 实名认证
     * @param $userInfo
     * @param $name
     * @param $card
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userAuth($userInfo,$name,$card){
        if($userInfo['is_auth'] == 1) return Response::fail('你已实名认证');
        $info = $this->usersData->where(['card'=>$card,'is_del'=>0])->find();
        if($info) return Response::fail('当前身份证号已被绑定');
        $result = $this->usersData->where(['id'=>$userInfo['id']])->update(['name'=>$name,'card'=>$card,'is_auth'=>1]);
        if($result) return Response::success('认证成功');
        return Response::fail('认证失败');
    }
}